166. Fraction to Recurring Decimal

1. Question

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

2. Examples

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

Example 4:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

Example 5:

Input: numerator = 1, denominator = 5
Output: "0.2"

3. Constraints

  • -231 <= numerator, denominator <= 231 - 1
  • denominator != 0

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fraction-to-recurring-decimal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

class Solution {
  public String fractionToDecimal(int numerator, int denominator) {
    long numeratorLong = (long) numerator;
    long denominatorLong = (long) denominator;
    if (numeratorLong % denominatorLong == 0) {
      return String.valueOf(numeratorLong / denominatorLong);
    }

    StringBuffer sb = new StringBuffer();
    if (numeratorLong * denominatorLong < 0) {
      sb.append('-');
    }

    // 整数部分
    numeratorLong = Math.abs(numeratorLong);
    denominatorLong = Math.abs(denominatorLong);
    long integerPart = numeratorLong / denominatorLong;
    sb.append(integerPart);
    sb.append('.');

    // 小数部分
    StringBuffer fractionPart = new StringBuffer();
    Map<Long, Integer> remainderIndexMap = new HashMap<Long, Integer>();
    long remainder = numeratorLong % denominatorLong;
    int index = 0;
    while (remainder != 0 && !remainderIndexMap.containsKey(remainder)) {
      remainderIndexMap.put(remainder, index);
      remainder *= 10;
      fractionPart.append(remainder / denominatorLong);
      remainder %= denominatorLong;
      index++;
    }
    if (remainder != 0) { // 有循环节
      int insertIndex = remainderIndexMap.get(remainder);
      fractionPart.insert(insertIndex, '(');
      fractionPart.append(')');
    }
    sb.append(fractionPart.toString());

    return sb.toString();
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""